package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext_id获取;
import com.itheima.reggie.common.CustomException_自定义异常;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.pojo.*;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @Author: cl
 * @Date: 2022/4/5 - 04 - 05
 * @Description:
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders_订单>
        implements OrderService {

    //购物车
    @Autowired
    private ShoppingCartService shoppingCartService;

    //用户
    @Autowired
    private UserService userService;

    //用户地址
    @Autowired
    private AddressBookService addressBookService;

    //订单明细
    @Autowired
    private OrderDetailService orderDetailService;

    //菜品
    @Autowired
    private DishService dishService;

    //套餐
    @Autowired
    private SetmealService setmealService;


    /**
     * 用户下单(1、更新订单表 2、更新订单详细表  3、删除购物车表)
     * 前端只发过来了addressBookId地址表id  和 付款方式  其他信息去数据库查询
     *
     * @param orders
     */
    @Transactional
    @Override
    public void submit(Orders_订单 orders) {

        //1、获取用户id
        Long userId = BaseContext_id获取.getCurrentId();

        //2、查询当前用户的购物车数据
        List<ShoppingCart_购物车> shoppingCart_购物车s = shoppingCartService.list(
                Wrappers.<ShoppingCart_购物车>lambdaQuery()
                        .eq(ShoppingCart_购物车::getUserId, userId)
        );
        /**
         * 月售
         */

        for (ShoppingCart_购物车 item : shoppingCart_购物车s) {
            Long dishId = item.getDishId();
            if (dishId != null) {
                Dish_菜品 one = dishService.getOne(
                        Wrappers.<Dish_菜品>lambdaQuery()
                                .eq(Dish_菜品::getId, item.getDishId())
                );
                dishService.update(
                        Wrappers.<Dish_菜品>lambdaUpdate()
                                .eq(Dish_菜品::getId, item.getDishId())
                                .set(Dish_菜品::getSaleNum, one.getSaleNum() + item.getNumber())
                );
            } else {
                Setmeal_套餐 one = setmealService.getOne(
                        Wrappers.<Setmeal_套餐>lambdaQuery()
                                .eq(Setmeal_套餐::getId, item.getSetmealId())
                );
                setmealService.update(
                        Wrappers.<Setmeal_套餐>lambdaUpdate()
                                .eq(Setmeal_套餐::getId, item.getSetmealId())
                                .set(Setmeal_套餐::getSaleNum, one.getSaleNum() + item.getNumber())
                );
            }

        }




        //判断购物车里面有没有商品
        if (shoppingCart_购物车s == null) {
            throw new CustomException_自定义异常("购物车为空，不能下单！");
        }

        //3、查询用户的数据
        User_用户 user = userService.getById(userId);

        //4、查询地址数据
        Long addressBookId = orders.getAddressBookId();
        AddressBook_用户地址 addressBook = addressBookService.getById(addressBookId);

        if (addressBook == null) {
            throw new CustomException_自定义异常("用户地址信息有误，不能下单！");
        }

        long orderId = IdWorker.getId(); //订单号

        //计算商品的总金额
        AtomicInteger amount = new AtomicInteger(0);//线程安全计数器

        //5、组装订单明细信息
        List<OrderDetail_订单明细> orderDetail_订单明细s = shoppingCart_购物车s.stream().map((item) -> {
            OrderDetail_订单明细 orderDetail_订单明细 = new OrderDetail_订单明细();

            orderDetail_订单明细.setOrderId(orderId);

//            orderDetail_订单明细.setNumber(item.getNumber());
//            orderDetail_订单明细.setDishFlavor(item.getDishFlavor());
//            orderDetail_订单明细.setDishId(item.getDishId());
//            orderDetail_订单明细.setSetmealId(item.getSetmealId());
//            orderDetail_订单明细.setName(item.getName());
//            orderDetail_订单明细.setImage(item.getImage());
//            orderDetail_订单明细.setAmount(item.getAmount());

            //直接用工具类拷贝
            BeanUtils.copyProperties(item, orderDetail_订单明细);

            //计算总金额
            amount.addAndGet(item.getAmount().multiply(
                    new BigDecimal(item.getNumber())
            ).intValue());
            return orderDetail_订单明细;
        }).collect(Collectors.toList());

        //6、组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //当前订单状态
        orders.setStatus(2);
        //总金额   BigDecimal计算精度比较高
        orders.setAmount(new BigDecimal(amount.get()));
        orders.setUserId(userId);
        //订单号就用的id
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        //收货人
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        //收货地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //向订单表插入数据，一条数据
        this.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetail_订单明细s);

        //清空购物车数据
        shoppingCartService.remove(
                Wrappers.<ShoppingCart_购物车>lambdaQuery()
                        .eq(ShoppingCart_购物车::getUserId, userId));

    }

    /**
     * 获取订单和商品数量
     *
     * @param page
     * @param pageSize
     * @return
     */
    @Override
    public Page getWithDish(int page, int pageSize) {
        Long userId = BaseContext_id获取.getCurrentId();
        Page pageInfo = new Page(page, pageSize);

        this.page(pageInfo,
                Wrappers.<Orders_订单>lambdaQuery()
                        .eq(Orders_订单::getUserId, userId)
                        .orderByDesc(Orders_订单::getOrderTime)
        );

        //获取订单明细中的商品数量   订单明细

        List<Orders_订单> orders = pageInfo.getRecords();
        orders = orders.stream().map((item) -> {
            //商品数量
//            int count = orderDetailService.count(
//                    Wrappers.<OrderDetail_订单明细>lambdaQuery()
//                            .eq(OrderDetail_订单明细::getOrderId, item.getId())
//            );
//            item.setSumNum(count);
            //商品明细
            List<OrderDetail_订单明细> list = orderDetailService.list(
                    Wrappers.<OrderDetail_订单明细>lambdaQuery()
                            .eq(OrderDetail_订单明细::getOrderId, item.getId())
            );
            //商品总数量
            int count = 0;
            for (OrderDetail_订单明细 orderDetail : list) {
                count += orderDetail.getNumber();
            }

            item.setSumNum(count);
            item.setOrderDetails(list);
            return item;
        }).collect(Collectors.toList());

        pageInfo.setRecords(orders);


        return pageInfo;
    }
}
